import type { RouteRecordRaw } from 'vue-router'
import { defineStore } from 'pinia'

export const useKeepAliveStore = defineStore('routeStore', () => {
  /**
   * 已缓存的路由
   */
  const cachedViews = ref<string[]>([])
  /**
   * 添加缓存路由
   * @param route
   */
  const addCachedView = (route: RouteRecordRaw) => {
    if (!route.meta?.keepAlive) return

    if (cachedViews.value.includes(route.name)) return

    cachedViews.value.push(route.name as string)
    console.log('cachedViews.value', cachedViews.value)
  }
  const addView = (route: RouteRecordRaw) => {
    addCachedView(route)
  }
  /**
   * 移除缓存路由
   * @param route
   */
  const removeCachedView = (route: RouteRecordRaw) => {
    const findResultIndex = cachedViews.value.findIndex((item) => item === route.name)
    if (findResultIndex > -1) {
      cachedViews.value.splice(findResultIndex, 1)
    }
  }
  const removeView = (route: RouteRecordRaw) => {
    removeCachedView(route)
  }
  const clearViews = () => {
    cachedViews.value = []
  }
  return {
    cachedViews,
    addView,
    removeView,
    clearViews
  }
})
